// 哈希表；时间复杂度O(n + m)；空间复杂度O(n + m)

class Solution {
public:
    bool wordPattern(string pattern, string s) {
        unordered_map<char, string> ch2str;
        unordered_map<string, char> str2ch;
        int n = s.size(), pos1 = 0;
        for (auto& c: pattern) {
            if (pos1 >= n) return false;
            int pos2 = pos1;
            while (pos2 != n && s[pos2] != ' ' ) {
                pos2++;
            }
            string str = s.substr(pos1, pos2 - pos1);
            if (ch2str.count(c) && ch2str[c] != str) {
                    return false;
                }
            if (str2ch.count(str) && str2ch[str] != c) {
                    return false;
                }
            ch2str[c] = str;
            str2ch[str] = c;
            pos1 = pos2 + 1;
        }
        return pos1 >= n;
    }
};